package com.stu.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

public class HorBarView extends View {

	private Paint outlinePaint, fillPaint, grabPaint;
	private int value, width, height;
	private Rect outlineRect, fillRect, grabRect;
	private final static int border = 2, grabWidth = 10, grabCenter = 5;
	
	public HorBarView(Context context) {
		super(context);
		init();
	}

	public HorBarView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public HorBarView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	/**
	 * @param v Value between 0 and 100
	 */
	public void setValue( int v ) {
		value = v;
		doCalc();
		invalidate();
	}
	
	private void init() {
		width = 100;
		height = 20;
		value = 0;
		outlineRect = new Rect();
		outlineRect.top = 0;
		outlineRect.left = 0;
		outlineRect.bottom = height;
		grabRect = new Rect();
		grabRect.top = 0;
		grabRect.bottom = height;
		fillRect = new Rect();
		fillRect.left = border;
		fillRect.top = border;
		fillRect.bottom = height - border;

		fillPaint = new Paint();
		fillPaint.setColor(Color.BLUE);
		fillPaint.setStyle(Paint.Style.FILL);

		grabPaint = new Paint();
		grabPaint.setColor(Color.GRAY);
		grabPaint.setStyle(Paint.Style.FILL);

		outlinePaint = new Paint();
		outlinePaint.setColor(Color.BLACK);
		outlinePaint.setStrokeWidth(border);
		outlinePaint.setStyle(Paint.Style.STROKE);
	}

	private void doCalc() {
		int fillX = Math.round(((float)value / 100) * width) - border;
		fillRect.right = fillX - grabCenter;
		if( fillRect.right < 0 )
			fillRect.right = 0;
		grabRect.left = fillRect.right;
		grabRect.right = grabRect.left + grabWidth;
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(width, height);
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		width = w;
		height = h;
		outlineRect.right = w;
		doCalc();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawRect(outlineRect, outlinePaint);
		canvas.drawRect(fillRect, fillPaint);
		canvas.drawRect(grabRect, grabPaint);
	}
}
